var express = require('express');
var router = express.Router();
const { VAPID_PUBLIC_KEY, VAPID_PRIVATE_KEY } = require('../config')
const fs = require('fs')
const path = require('path')
const webpush = require('web-push')
const dbPath = path.join(__dirname, '../db.json')

/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('index', { title: 'Express' });
});

// 获取公钥
router.get('/get-public-key', function(req, res) {
  res.send(VAPID_PUBLIC_KEY);
})

// 储存订阅消息
router.post('/save-subscription', function(req, res) {
  const data = JSON.parse(fs.readFileSync(dbPath))
  data.push(req.body.subscription)
  fs.writeFileSync(dbPath, JSON.stringify(data, null, 2))
  res.sendStatus(201)
})

// 发送消息
router.post("/send-push", (req, res) => { 
  const options = { 
    vapidDetails: { 
      subject: "https://kuohao-wu.github.io/", 
      publicKey: VAPID_PUBLIC_KEY, 
      privateKey: VAPID_PRIVATE_KEY 
    }, 
    TTL: 60 * 60 
  }; 
  const subscriptions = JSON.parse(fs.readFileSync(dbPath)) // 获取存储的所有订阅信息 
  const msg = req.body.content; 
 
  subscriptions.map(subscription => {
     // 对每一个订阅者进行消息发送 
     webpush 
     .sendNotification(subscription, msg, options) 
     .then(() => { 
       res.status(200).send({ success: true }); 
     }) 
     .catch(err => { 
       if (err.statusCode) { 
         // 订阅信息无效，则删除存储在应用服务器的订阅信息 
         if (err.statusCode == 404 || err.statusCode == 410) { 
           db.delete(subscription); 
         } 
         res.status(err.statusCode).send(err.body); 
       } else { 
         res.status(400).send(err.message); 
       } 
     }); 
 }); 
}); 

module.exports = router;
